package com.zzl.admin.listener;

import com.gitee.yongzhuzl.commonutil.util.empty.EmptyUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import javax.websocket.Session;
import java.io.IOException;

/**
 * description: redis订阅消息监听
 * @author 朱正磊
 * @date 2022-02-07 14:57:51
 */
@Slf4j
@Data
public class SubscribeListener implements MessageListener {

    /**
     * 当前websocket的session
     */
    private Session session;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String msg = new String(message.getBody());
        if (EmptyUtil.isNotEmpty(session) && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("发送消息异常，msg = {}, e = {}", msg, e);
            }
        }
    }

}
